package com.foreveross.ccjd.chart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class CircleView extends View {

	private RectF mBigOval;
	private float mStart = 90;
	private float mSweep;
	private float mEndSweep;
	boolean initfinish;
	private static float SWEEP_INC = 1;
	private float mInc;
	private TextView mTv;

	public CircleView(Context context, int radius, float percentage, TextView tv) {
		super(context);
		mTv = tv;
		mInc = 5f / 9f;
		init(radius, percentage);
	}

	private int mPercentage;

	private void init(int radius, float percentage) {
		if (percentage > 1) {
			return;
		}
		// mStart = mStart - SWEEP_INC;
		int per = (int) (percentage * 100);
		mPercentage = per;
		int diameter = 2 * radius;
		setLayoutParams(new LayoutParams(diameter, diameter));
		float sweep = 0;
		if (percentage <= 0.5f) {
//			sweep = 90 * (1 - percentage * 2);
			mEndSweep = 90-per*(9/5f);
		} else {
//			sweep = 360 - 90 * ((percentage - 0.5f) * 2);
			mEndSweep =  270+(100-per)*(9/5f);
		}
//		mEndSweep = sweep;
		mBigOval = new RectF(0, 0, diameter, diameter);
		initfinish = true;
	}

	private void drawArcs(Canvas canvas, RectF oval, boolean useCenter,
			Paint paint) {
		canvas.drawArc(oval, mStart, mSweep, useCenter, paint);
	}

	private float mPer;

	@Override
	protected void onDraw(Canvas canvas) {
		// canvas.drawColor(Color.WHITE);
		if (!initfinish) {
			return;
		}
		// Paint paint = new Paint();
		// paint.setColor(Color.BLACK);
		// canvas.drawArc(mBigOval, 0, 360, true, paint);

		Paint red = new Paint();
		// red.setAntiAlias(true);
		// red.setStyle(Paint.Style.FILL);
		red.setColor(0x88FF0000);
		drawArcs(canvas, mBigOval, false, red);
		boolean finish = false;
		if (mStart >= 0 && mStart <= 90) {

			if (mStart <= mEndSweep && mEndSweep <= 90) {
				finish = true;
			} else {
				mStart -= SWEEP_INC;
			}
		} else if (mStart < 0) {
			mStart = 360 - SWEEP_INC;
			// mStart += SWEEP_INC;
		} else if (mStart > 270 && mStart <= 360) {
			if (mStart >= mEndSweep) {
				mStart = 360 - ((360 - mStart) + SWEEP_INC);
			} else {
				finish = true;
			}
		}
		if (!finish) {
			mSweep += SWEEP_INC * 2;
			System.out.println(mSweep);
			mPer += mInc;
			mTv.setText(String.valueOf((int) mPer));
		} else {
			mTv.setText(String.valueOf(mPercentage));
		}
		invalidate();
	}
}
